class Solution
{
public:
    int closestMeetingNode(vector<int> &edges, int node1, int node2)
    {
        map<int, int> node1Reach;
        map<int, int> node2Reach;
        node1Reach[node1] = 0;
        node2Reach[node2] = 0;
        int n = edges.size();
        int distance = 0;
        while (node1 != -1 || node2 != -1)
        {
            ++distance;
            if (node1 != -1)
            {
                node1 = edges[node1];
                if (node1 != -1)
                {
                    if (node1Reach.count(node1))
                    {
                        node1 = -1;
                    }
                    else
                    {
                        node1Reach[node1] = distance;
                    }
                }
            }

            if (node2 != -1)
            {
                node2 = edges[node2];
                if (node2 != -1)
                {
                    if (node2Reach.count(node2))
                    {
                        node2 = -1;
                    }
                    else
                    {
                        node2Reach[node2] = distance;
                    }
                }
            }
        }
        int minMaxDist = n;
        int minMaxDistNode = -1;
        for (auto &[node, dist] : node1Reach)
        {
            if (node2Reach.count(node))
            {
                int maxDist = max(dist, node2Reach[node]);
                if (maxDist < minMaxDist)
                {
                    minMaxDist = maxDist;
                    minMaxDistNode = node;
                }
            }
        }
        return minMaxDistNode;
    }
};